package com.avic.modules.equipment.rest;

import com.avic.modules.equipment.service.StationService;
import com.avic.modules.equipment.service.dto.StationQueryCriteria;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangzikang
 * @date 2022-08-14
 */
@Api(tags = "设备管理: 站位接口")
@RestController
@RequestMapping("/api/equipment/station")
@AllArgsConstructor
public class StationController {

    private final StationService stationService;
    private final StringRedisTemplate stringRedisTemplate;

    /**
     * 查看站位
     * @param criteria
     * @return
     */
    @ApiOperation("查看站位")
    @GetMapping("/all")
    public ResponseEntity<Object> getStation(StationQueryCriteria criteria){
        return new ResponseEntity<>(stationService.queryAll(criteria), HttpStatus.OK);
    }

    @GetMapping("/test")
    public String getTest(){
        String zzk = "zhangzikang";

        String clientId = UUID.randomUUID().toString();
        try {
            Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(zzk, clientId, 10, TimeUnit.SECONDS);
            if(!aBoolean){
                return "人数太多请稍后再试";
            }
            int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));
            if(stock >0){
                int realStock = stock -1;
                stringRedisTemplate.opsForValue().set("stock", realStock + "");

                return "库存剩余" + realStock;
            } else {


                return "库存不足";
            }
        } finally {
            if(clientId.equals(stringRedisTemplate.opsForValue().get(zzk))){
                stringRedisTemplate.delete(zzk);
            }
        }

    }
}
